/**
 * Created by artheru on 2017/6/25.
 */

function eventsInit() {
    let eventMap = {};
    let ret = {};

    ret.emit = function (content, ...path) {
        //Async post
        let pointer = eventMap;
        for (let i = 0; i < path.length; ++i) {
            let eventName = path[i];
            if (pointer[eventName])
                pointer = pointer[eventName];
            else {
                console.log("Warning: Event not emit, no such event:" + path.join("."));
                return
            }
        }

        pointer(content);
    }

    //Register an event handler.
    ret.register = function (fun, ...path) {
        let pointer = eventMap;
        for (let i = 0; i < path.length - 1; ++i) {
            let eventName = path[i];
            if (!pointer[eventName])
                pointer[eventName] = {};
            pointer = pointer[eventName];
        }
        pointer[path[path.length - 1]] = fun;
    }

    //Unregister an event handler.
    ret.unregister = function (fun, ...path) {
        let pointer = eventMap;
        for (let i = 0; i < path.length - 1; ++i) {
            let eventName = path[i];
            if (pointer[eventName])
                pointer = pointer[eventName];
            else {
                console.log("Unregister Failed, no such event:" + path.join("."));
                return
            }
            pointer = pointer[eventName];
        }
        pointer[path[path.length]] = undefined;
    };

    return ret;
}

export default function init(ctx) {
    let eventSys=eventsInit();
    let ret = {};

    ret.waitFor=(name)=>new Promise((res,rej)=>eventSys.register((pck)=>pck.type=="throw"?rej(pck.data):res(pck.data), name));
    ret.trigger=(name, data)=>eventSys.emit({type:"trigger",data}, name);
    ret.throw=(name, data)=>eventSys.emit({type:"throw",data}, name);
    console.log("event system loaded...");
    return ret;
}